<script setup lang="ts">
import { computed, onMounted, reactive, shallowRef } from 'vue'

import { ColumnHeightOutlined, PlusOutlined, ReloadOutlined } from '@ant-design/icons-vue'
import type { MenuProps, PaginationProps, TableProps } from 'ant-design-vue'
import RoleForm from './role-from.vue'
import RoleMenuTree from './role-menu-tree.vue'
import { useAppStore } from '~/stores/app'
import { useLayoutMenu } from '~/stores/layout-menu'
import { useLayoutMenuProvide } from '~/components/page-container/context'
import type { ConsultTableModel } from '~@/api/list/table-list'
import type { FormState } from '~@/api/role/role'
import { getRoleInfoApi, roleDeleteApi } from '~@/api/role/role'

const layoutMenu = useLayoutMenu()
const appStore = useAppStore()
useLayoutMenuProvide(layoutMenu, appStore)

const message = useMessage()
const columns = shallowRef([
  {
    title: '角色名称',
    dataIndex: 'roleName',
  },
  {
    title: '角色编码',
    dataIndex: 'roleCode',
  },
  {
    title: '状态',
    dataIndex: 'statusFlag',
  },
  {
    title: '备注',
    dataIndex: 'remark',
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 250,
  },
])
const loading = shallowRef(false)
const total = ref(0)
const pagination = reactive<PaginationProps>({
  pageSize: 10,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: total.value,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: total => `总数据位：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef<ConsultTableModel[]>([])

const tableSize = ref<string[]>(['large'])
const sizeItems = ref<MenuProps['items']>([
  {
    key: 'large',
    label: '默认',
    title: '默认',
  },
  {
    key: 'middle',
    label: '中等',
    title: '中等',
  },
  {
    key: 'small',
    label: '紧凑',
    title: '紧凑',
  },
])

const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))

async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await getRoleInfoApi(pagination.current, pagination.pageSize)
    dataSource.value = data.list ?? []
    total.value = data.total ?? 0
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

async function onSearch() {
  pagination.current = 1
  await init()
}

/**
 * 删除功能
 *  @param record
 *
 */
async function handleDelete(record: FormState) {
  const close = message.loading('删除中......')
  try {
    const res = await roleDeleteApi(record!.roleId)
    if (res.code === 200)
      await init()
    message.success('删除成功')
  }
  catch (e) {
    console.log(e)
  }
  finally {
    close()
  }
}

const roleFormModal = ref<InstanceType<typeof RoleForm>>()
const roleMenuTreeModal = ref<InstanceType<typeof RoleMenuTree>>()
const menuTreeVisible = ref(false)
const currentRoleId = ref<number | string>(0)

function handleUpdate(record: FormState) {
  roleFormModal.value?.handleUpdate(record)
}

function handleAdd() {
  roleFormModal.value?.handleAdd()
}

// 打开菜单绑定弹窗
function handleBindMenu(record: FormState) {
  console.log(record)
  currentRoleId.value = record.roleId
  menuTreeVisible.value = true
}

// 菜单绑定成功回调
function onMenuBindSuccess() {
  message.success('角色菜单绑定成功')
}

/**
 * 密度切换
 *
 */
const handleSizeChange: MenuProps['onClick'] = (e) => {
  tableSize.value[0] = e.key as string
}

/**
 * 过滤
 *
 */
function filterAction(value: string[]) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex)) {
      // 为true时，循环遍历的值会暴露出去
      return true
    }
    return false
  })
}

// 备份columns
const filterColumns = ref(filterAction(getCheckList.value))

onMounted(() => {
  init()
})

const formState = reactive<FormState>({
  roleId: undefined,
  roleName: '',
  roleCode: '',
  statusFlag: 1,
  remark: '',
})
</script>

<template>
  <page-container>
    <a-card title="查询表格">
      <template #extra>
        <a-space size="middle">
          <a-button type="primary" @click="handleAdd">
            <template #icon>
              <PlusOutlined />
            </template>
            新增
          </a-button>
          <a-tooltip title="刷新">
            <ReloadOutlined @click="onSearch" />
          </a-tooltip>
          <a-tooltip title="密度">
            <a-dropdown trigger="click">
              <ColumnHeightOutlined />
              <template #overlay>
                <a-menu v-model:selected-keys="tableSize" :items="sizeItems" @click="handleSizeChange" />
              </template>
            </a-dropdown>
          </a-tooltip>
        </a-space>
      </template>
      <a-table :loading="loading" :columns="filterColumns" :data-source="dataSource" :pagination="pagination" :size="tableSize[0] as TableProps['size']">
        <template #bodyCell="scope">
          <template v-if="scope?.column?.dataIndex === 'action'">
            <div flex gap-2>
              <a c-blue @click="handleUpdate(scope?.record as FormState)">
                修改
              </a>
              <a c-error @click="handleDelete(scope?.record as FormState)">
                删除
              </a>
              <a @click="handleBindMenu(scope?.record as FormState)">
                绑定菜单
              </a>
            </div>
          </template>
          <template v-else-if="scope?.column?.dataIndex === 'statusFlag'">
            <span v-if="scope?.record?.statusFlag === 1" class="text-green-600">启用</span>
            <span v-else-if="scope?.record?.statusFlag === 2" class="text-red-600">禁用</span>
            <span v-else>{{ scope?.record?.statusFlag }}</span>
          </template>
        </template>
      </a-table>
    </a-card>
    <RoleForm ref="roleFormModal" @init="init" />

    <RoleMenuTree
      ref="roleMenuTreeModal"
      v-model:visible="menuTreeVisible"
      :role-id="currentRoleId"
      @close="() => (menuTreeVisible.value = false)"
      @success="onMenuBindSuccess"
    />
  </page-container>
</template>
